package org.example.springcloud.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 *
 * @author Jandmla
 * Date: 2022/7/28
 * Time: 17:22
 * Description:
 */
@Slf4j
@Component
public class MyLoadBalancer implements LoadBalancer{

    private AtomicInteger integer = new AtomicInteger(0);

    public final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.integer.get();
            next = current >= Integer.MAX_VALUE ? 0 : current +1;
        }while (integer.compareAndSet(current,next));
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int size;
        if (null == serviceInstances || (size = serviceInstances.size()) == 0){
            log.error("没有存活的服务实例，请检查服务实例是否正常！");
            throw new RuntimeException("服务实例存活数不足！");
        }
        int index = getAndIncrement() % size;
        return serviceInstances.get(index);
    }
}